import {
  createRouter,
  createWebHashHistory
} from 'vue-router';
import {
  ElMessage
} from 'element-plus'
import storage from '../utils/storage'


const routes = [{
    path: '/',
    component: () => import('../views/main.vue'),
    meta: {
      title: '首页'
    },
    children: [{
        path: '',
        redirect: 'welcome'
      },
      {
        path: 'welcome',
        component: () => import('../views/welcome.vue'),
        meta: {
          title: '欢迎页'
        }
      },
      {
        path: 'user',
        component: () => import('../views/system/user.vue'),
        meta: {
          title: '用户管理'
        }
      },
      {
        path: 'menu',
        component: () => import('../views/system/menu.vue'),
        meta: {
          title: '菜单管理'
        }
      },
      {
        path: 'role',
        component: () => import('../views/system/role.vue'),
        meta: {
          title: '角色管理'
        }
      },
      {
        path: 'dept',
        component: () => import('../views/system/dept.vue'),
        meta: {
          title: '部门管理'
        }
      },
      {
        path: 'leave',
        component: () => import('../views/system/leave.vue'),
        meta: {
          title: '休假申请'
        }
      },
      {
        path: 'approve',
        component: () => import('../views/system/approve.vue'),
        meta: {
          title: '休假审核'
        }
      },
    ]
  },
  {
    path: '/login',
    component: () => import('../views/login.vue'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/404',
    component: () => import('../views/404.vue'),
    meta: {
      title: '页面不存在'
    }
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


// function checkPermission(path) {
//   let hasPermission = router.getRoutes().filter(route => route.path == path)
//   if (hasPermission) {
//     return true
//   } else {
//     return false
//   }
// }

router.beforeEach(async (to, from, next) => {
  // console.log(to, from)

  // if (router.hasRoute(to.path)) {
  //   document.title = to.meta.title;
  //   next();
  // } else {
  //   next('/404')
  // }

  const {
    meta,
    matched,
  } = to;
  let isMatched = matched && matched.length > 0; // 是否匹配路由
  let {
    isAuth
  } = (meta || {}); //是否需要登录

  const isLogin = storage.getItem('manager') || false //是否已登录
  // const id = localStorage.getItem("id");
  if (isMatched) {
    // 匹配到路由
    if (isAuth) {
      // 需要登录访问
      if (isLogin) {
        // 已登录访问
        next(); // 调用钩子函数
      } else {
        // 未登录访问
        ElMessage.error("用户未登录！");
        // 清除登录数据
        storage.clearAll()

        next("/login"); // 跳转登录
      }
    } else {
      // 不需要登录访问
      next(); // 调用钩子函数
    }
  } else {
    // 未匹配到路由
    if (isLogin) {
      // 已登录访问
      next("/"); // 跳转首页
    } else {
      // 未登录访问
      next("/login"); // 跳转登录页
    }
  }



  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title;
  }

});

export default router